﻿using System;
using Game.Actions;
using Game.Common;
using Game.Map;
using Game.Map.Extensions;
using Game.Objects;

namespace Game.Command.Internal
{
    public class AttackEventArgs : EventArgs
    {
        readonly Vehicle _Attacked;
        readonly Vehicle _Attacking;

        public AttackEventArgs(Vehicle attacked, Vehicle attacking)
        {
            _Attacked = attacked;
            _Attacking = attacking;
        }

        public Vehicle Attacked
        {
            get { return _Attacked; }
        }

        public Vehicle Attacking
        {
            get { return _Attacking; }
        }
    }

    public class AttackUnitCommand : GameCommand
    {
        public event EventHandler<AttackEventArgs> Attacked;

        readonly GamePath _Path;
        readonly IGameMap _GameMap;
        
        public AttackUnitCommand(IGameMap gameMap, GamePath path)
        {
            _GameMap = gameMap;
            _Path = path;
        }

        public GamePath Path
        {
            get { return _Path; }
        }

        public override string Name
        {
            get { return "Attack"; }
        }
        
        protected override ActionResult Execute(GameTurn turn,
                                                Context context)
        {
            context.ActionExecutor.Start(turn);

            var attackingField = _GameMap.Fields[_Path.FirstPoint];
            var attackedField = _GameMap.Fields[_Path.LastPoint];
            
            var v1 = attackingField.VehicleX().Vehicle;
            var v2 = attackedField.VehicleX().Vehicle;
            
            var attackingView = _GameMap.Views[v1.Owner];
            
            var attack = new UnitAttacksUnit(
                context.GameMapView, context.GameLevels, 
                attackingField, attackedField,
                attackingView);
            attack.DoCalculation();
            attack.SetResult(turn, context.ActionExecutor);

            if (Attacked != null)
            {
                var args = new AttackEventArgs(v2, v1);
                Attacked(this, args);
            }

            _GameMap.SelectedX().Selected = null;
            
            context.ActionExecutor.Done(turn, false);
            return new ActionResult(0, "");
        }


    }
}
